//
// Created by denglibin on 19-10-29.
//

/**
 *udp广播 服务
 **/

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <ctype.h>
#include <strings.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#define SERVER_PORT 8000
#define CLIENT_PORT 9000
#define MAX_LINE 1024
#define BROADCAST_IP "192.168.1.255" //广播地址 局域网内的机器都可以接收

static int main_(void){

    int sock_fd;
    struct sockaddr_in server_addr, client_addr;
    char buf[MAX_LINE] = "hello everyone";

    /*构造用于udp通信的套接字*/
    sock_fd = socket(AF_INET, SOCK_DGRAM, 0);

    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;/*IP V4*/
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);/*任意ip*/

    bind(sock_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));

    int flag = 1;
    /*设置socket选项, 让socket具备广播能力*/
    setsockopt(sock_fd, SOL_SOCKET, SO_BROADCAST, &flag, sizeof(flag));
    /*构造客户端ip 端口*/
    bzero(&client_addr, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(CLIENT_PORT);
    inet_pton(AF_INET, BROADCAST_IP, &client_addr.sin_addr.s_addr);

    /*发送数据包*/
    while (1){
        printf("send...\n");
        sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr*)&client_addr, sizeof(client_addr));
        sleep(1);
    }

    return 0;
}